package com.ljkj.cordial.chat.fresco;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.util.TypedValue;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.nic.view.util.glide.GlideUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/12/16 15:32
 */
public class ImageLoader {

    static int mDefFriendId;
    static int mDefGroupId;

    public static void config(@DrawableRes int defFriendId, @DrawableRes int defGroupId) {
        mDefFriendId = defFriendId;
        mDefGroupId = defGroupId;
    }

    private volatile static ImageLoader instance;

    public static ImageLoader getInstance() {
        if (instance == null) {
            synchronized (ImageLoader.class) {
                if (instance == null) {
                    instance = new ImageLoader();
                }
            }
        }
        return instance;
    }

    public void displayLocalAvatar(String localPath, ImageView iv) {
        if (!TextUtils.isEmpty(localPath)) {
            Bitmap localBitmap = getLocalBitmap(localPath);
            if (localBitmap != null) {
                loadCropCircle(iv, localBitmap);
            } else {
                if (ImageLoader.mDefFriendId != 0)
                    iv.setImageResource(ImageLoader.mDefFriendId);
            }
        } else {
            if (ImageLoader.mDefFriendId != 0)
                iv.setImageResource(ImageLoader.mDefFriendId);
        }
    }

    public void displayGroupMemberAvatar(String groupId, String memberId, String downloadPath, ImageView iv) {
        if (TextUtils.isEmpty(downloadPath)) {
            if (ImageLoader.mDefGroupId != 0)
                iv.setImageResource(ImageLoader.mDefGroupId);
            return;
        }
        GroupMemberTable gm = GroupMemberTable.query(groupId, memberId);
        if (gm != null && !TextUtils.isEmpty(gm.getGroupMemberUserId())) {
            String serverPath = gm.getGroupMemberAvatar();
            if (!TextUtils.isEmpty(serverPath)) {
                final AlbumTableBean albumTableBean = AlbumManageUtil.getFileTableByPath(gm.getGroupMemberAvatar());
                if (null != albumTableBean) {
                    String clientPath = albumTableBean.getMPath();
                    if (TextUtils.isEmpty(serverPath) || !serverPath.equals(downloadPath) || TextUtils.isEmpty(clientPath) || !new File(clientPath).exists()) {
                        ImageDownloader.displayGroupMemberAvatarAfterDownload(albumTableBean, downloadPath, gm, iv);
                    } else {
                        Bitmap localBitmap = getLocalBitmap(clientPath);
                        if (localBitmap != null) {
                            loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefGroupId != 0)
                                iv.setImageResource(ImageLoader.mDefGroupId);
                        }
                    }
                } else {
                    ImageDownloader.displayGroupMemberAvatarAfterDownload(null, downloadPath, gm, iv);
                }
            } else {
                ImageDownloader.displayGroupMemberAvatarAfterDownload(null, downloadPath, gm, iv);
            }
        } else {
            if (mDefGroupId != 0)
                iv.setImageResource(mDefGroupId);
        }
    }

    public void displayFriendAvatar(String friendUserId, String downloadPath, ImageView iv) {
        if (TextUtils.isEmpty(downloadPath)) {
            if (ImageLoader.mDefFriendId != 0)
                iv.setImageResource(ImageLoader.mDefFriendId);
            return;
        }
        FriendTable f = FriendTable.getTableByFriendUserId(friendUserId);
        if (f != null && !TextUtils.isEmpty(f.getFriendUserId())) {
            String serverPath = f.getFriendAvatar();
            if (!TextUtils.isEmpty(serverPath)) {
                final AlbumTableBean albumTableBean = AlbumManageUtil.getFileTableByPath(f.getFriendAvatar());
                if (null != albumTableBean) {
                    String clientPath = albumTableBean.getMPath();
                    if (TextUtils.isEmpty(serverPath) || !serverPath.equals(downloadPath) || TextUtils.isEmpty(clientPath) || !new File(clientPath).exists()) {
                        ImageDownloader.displayFriendAvatarAfterDownload(albumTableBean, downloadPath, f, iv);
                    } else {
                        Bitmap localBitmap = getLocalBitmap(clientPath);
                        if (localBitmap != null) {
                            loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefFriendId != 0)
                                iv.setImageResource(ImageLoader.mDefFriendId);
                        }
                    }
                } else {
                    ImageDownloader.displayFriendAvatarAfterDownload(null, downloadPath, f, iv);
                }
            } else {
                ImageDownloader.displayFriendAvatarAfterDownload(null, downloadPath, f, iv);
            }
        } else {
            if (mDefFriendId != 0)
                iv.setImageResource(mDefFriendId);
        }
    }

    public void displayUserAvatar(String downloadPath, ImageView iv) {
        if (TextUtils.isEmpty(downloadPath)) {
            if (ImageLoader.mDefFriendId != 0)
                iv.setImageResource(ImageLoader.mDefFriendId);
            return;
        }
        UserTableBean u = UserTableBean.getCurrentUser();
        if (u == null || (TextUtils.isEmpty(u.getUserId()) && TextUtils.isEmpty(u.getTemporaryId()))) {
            if (ImageLoader.mDefFriendId != 0)
                iv.setImageResource(ImageLoader.mDefFriendId);
            return;
        }
        String avatarId = u.getAvatarId();
        try {
            if (!TextUtils.isEmpty(avatarId)) {
                long id = Long.parseLong(avatarId);
                final AlbumTableBean albumTableBean = AlbumTableBean.queryById(id);
                if (albumTableBean != null) {
                    String serverPath = albumTableBean.getMUrl();
                    String clientPath = albumTableBean.getMPath();
                    if (TextUtils.isEmpty(serverPath) || !serverPath.equals(downloadPath) || TextUtils.isEmpty(clientPath) || !new File(clientPath).exists()) {
                        ImageDownloader.displayUserAvatarAfterDownload(albumTableBean, downloadPath, u, iv);
                    } else {
                        Bitmap localBitmap = getLocalBitmap(clientPath);
                        if (localBitmap != null) {
                            loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefFriendId != 0)
                                iv.setImageResource(ImageLoader.mDefFriendId);
                        }
                    }
                } else {
                    ImageDownloader.displayUserAvatarAfterDownload(null, downloadPath, u, iv);
                }
            } else {
                ImageDownloader.displayUserAvatarAfterDownload(null, downloadPath, u, iv);
            }
        } catch (NumberFormatException e) {
            Logger.print(e.getLocalizedMessage());
            if (ImageLoader.mDefFriendId != 0)
                iv.setImageResource(ImageLoader.mDefFriendId);
        }
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    static void loadCropCircle(ImageView imageAware, Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
//        int dp8 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, imageAware.getResources().getDisplayMetrics());
        int dp4 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, imageAware.getResources().getDisplayMetrics());
        Glide.with(ChatApp.getInstance())
                .load(bytes)
                .placeholder(imageAware.getDrawable()) //加载中
                .error(R.drawable.ic_loading_fail)//加载失败
                .fallback(R.drawable.ic_loading_fail)//加载为空
                .priority(Priority.HIGH)//加载的优先等级
                .diskCacheStrategy(DiskCacheStrategy.NONE)//缓存类型
//                .bitmapTransform(new CropCircleTransformation(ChatApp.getInstance()))
                .bitmapTransform(new RoundedCornersTransformation(ChatApp.getInstance(), dp4, 0))
                .dontAnimate()
                .into(imageAware);
    }
}
